const Router = require('@koa/router');
const { Comment } = require('../databases/index');
const { Op } = require('sequelize');

const commentRouter = new Router({
    prefix: '/comment'
});
// 获取所有评论（支持分页和模糊查询）
commentRouter.get('/', async (ctx) => {
    const { page = 1, pageSize = 10, keyword = '', sightId, userId, replyToCommentId, sightName } = ctx.query;
    const offset = (parseInt(page) - 1) * parseInt(pageSize);
    const limit = parseInt(pageSize);
    
    // 构建查询条件
    const whereCondition = {};
    if (keyword) {
        whereCondition.content = {
            [Op.like]: `%${keyword}%`
        };
    }
    if (sightId) whereCondition.sightId = sightId;
    if (userId) whereCondition.userId = userId;
    if (replyToCommentId) whereCondition.replyToCommentId = replyToCommentId;
    
    // 景区名称模糊搜索，联表查询
    let include = [];
    if (sightName && sightName.trim() !== '') {
        const { Sight } = require('../databases');
        include.push({
            model: Sight,
            as: 'sight',
            where: {
                name: { [Op.like]: `%${sightName.trim()}%` }
            },
            required: true
        });
    }
    const { count, rows } = await Comment.findAndCountAll({
        where: whereCondition,
        include,
        offset,
        limit,
        order: [['commentId', 'DESC']]
    });
    
    ctx.body = {
        code: 200,
        message: '获取成功',
        data: {
            list: rows,
            total: count,
            page: parseInt(page),
            pageSize: parseInt(pageSize)
        }
    };
});
// 添加评论
commentRouter.post('/add', async (ctx,next) => {
    const { userId, sightId, content, likeCount, replyCount, replyToCommentId } = ctx.request.body;
    try {
        const currentComment = await Comment.create({
            userId,
            sightId,
            content,
            likeCount: likeCount || 0,
            replyCount: replyCount || 0,
            replyToCommentId
        });
        // 新增评论时，如果有 replyToCommentId，则目标评论 replyCount +1
        if (replyToCommentId) {
            await Comment.increment('replyCount', { by: 1, where: { commentId: replyToCommentId } });
        }
        ctx.body = {
            message: 'Add comment',
            data: currentComment
        }
    } catch (error) {
        ctx.body = {
            message: 'Add comment failed',
            error: error.message
        }
    }
});
// 删除评论
commentRouter.delete('/delete/:commentId', async (ctx,next) => {
    const { commentId } = ctx.params;
    // 查询该评论的 replyToCommentId
    const comment = await Comment.findByPk(commentId);
    let replyToCommentId = null;
    if (comment) replyToCommentId = comment.replyToCommentId;
    const deletedCount = await Comment.destroy({ where: { commentId } });
    // 删除评论时，如果有 replyToCommentId，则目标评论 replyCount -1
    if (deletedCount && replyToCommentId) {
        await Comment.decrement('replyCount', { by: 1, where: { commentId: replyToCommentId } });
    }
    if (deletedCount) {
        ctx.body = {
            message: 'Delete comment',
            data: { commentId }
        }
    } else {
        ctx.body = {
            message: 'Comment not found',
            data: { commentId }
        }
    }

});
//修改评论
commentRouter.put('/update/:commentId', async (ctx,next) => {
        const { commentId } = ctx.params;
        const { userId, sightId, content, likeCount, replyCount, replyToUserId } = ctx.request.body;
        try {
            const { userId, sightId, content, likeCount, replyCount, replyToCommentId } = ctx.request.body;
            const updatedCount = await Comment.update({
                userId,
                sightId,
                content,
                likeCount,
                replyCount,
                replyToCommentId
            }, { where: { commentId } });
            if (updatedCount) {
                ctx.body = {
                    message: 'Update comment',
                    data: { commentId, userId, sightId, content, likeCount, replyCount, replyToCommentId }
                }
            } else {
                ctx.body = {
                    message: 'Comment not found',
                    data: { commentId }
                }
            }
        } catch (error) {
            ctx.body = {
                message: 'Update comment failed',
                error: error.message
            }
        }
});


module.exports = commentRouter;